<template>
  <div class="history-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <h1 class="app-title">DR眼底医疗健康档案</h1>
      <div class="action-container">

        <!-- 新增操作按钮组 -->
        <div class="action-buttons">
          <div class="search-group">
            <el-input
                v-model="searchName"
                placeholder="按姓名搜索"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>

            <el-input
                v-model="searchId"
                placeholder="按身份证号搜索"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
          </div>
          <el-tooltip content="返回" placement="bottom">
            <el-button
                type="info"
                size="large"
                circle
                plain
                @click="handleReturn"
                class="return-button"
            >
              <el-icon :size="32" style="color: dodgerblue"><Back /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="上传图片（可多选）" placement="bottom">
            <el-button
                type="primary"
                circle
                plain
                @click="handleUploadClick"
                class="flat-button"
            >
              <el-icon :size="32" style="color: white"><Upload /></el-icon>
            </el-button>
          </el-tooltip>
          <input
            ref="imageInput"
            type="file"
            hidden
            accept="image/jpeg"
            multiple
            @change="handleImageSelect"
          >
        </div>
      </div>
    </div>
    <!-- 卡片式数据展示 -->
    <div class="scroll-container">
      <transition-group
          name="staggered-fade"
          tag="div"
          class="card-view">
        <div
            v-for="(item, index) in filteredData"
            :key="item.id"
            class="data-card"
            :class="{ active: activeIndex === index }"
            @mouseenter="activeIndex = index"
            @mouseleave="activeIndex = -1"
            @click="makePDF(item)"
            :data-index="index"
        >
          <div class="card-header">
            <span class="record-id">#{{ item.id }}</span>
            <span class="upload-time">{{ item.uploadTime }}</span>
            <el-tag type="success" effect="plain" round :size="'large'">已分析完成</el-tag>
          </div>

          <div class="card-body">
            <div class="eye-preview">
              <div class="eye-container">
                <div class="eye-item">
                  <div class="eye-label">左眼</div>
                  <div class="image-container">
                    <img
                        v-if="item.left"
                        :src="item.left"
                        class="thumbnail-preview"
                        alt="左眼图像"
                        @error="handleImageError('left')"
                        @click.stop="handlePreviewImage(item.left)"
                    >
                    <div v-else class="image-missing">无左眼图像</div>
                  </div>

                </div>
                <div class="divider"></div>
                <div class="eye-item">
                  <div class="eye-label">右眼</div>
                  <div class="image-container">
                    <img
                        v-if="item.right"
                        :src="item.right"
                        class="thumbnail-preview"
                        alt="右眼图像"
                        @error="handleImageError('right')"
                        @click.stop="handlePreviewImage(item.right)"
                    >
                    <div v-else class="image-missing">无右眼图像</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="patient-info">
              <div class="info-item">
                <el-icon><User /></el-icon>
                <span>{{ item.username }}</span>
              </div>
              <div class="info-item">
                <el-icon><CreditCard /></el-icon>
                <span class="identification">{{ item.identification }}</span>
              </div>
            </div>
          </div>

          <div class="card-actions">
            <el-button type="primary" text @click.stop="handleView(item)">
              <template #icon><View /></template>
              查看详情
            </el-button>
            <el-button type="warning" text @click.stop="makePDF(item)">
              <template #icon><Document /></template>
              生成报告
            </el-button>
            <el-button type="success" text @click.stop="handleAIChat(item)">
              <template #icon><ChatLineRound /></template>
              AI小助手
            </el-button>
<!--            <el-button type="danger" text @click.stop="handleDelete(item)">-->
<!--              <template #icon><Delete /></template>-->
<!--              删除记录-->
<!--            </el-button>-->
          </div>
        </div>
      </transition-group>
    </div>
  </div>
  <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      width="auto"
      class="adaptive-dialog"
      @click="dialogVisible = false"
  >
    <div class="image-preview-container">
      <img :src="selectedImage" class="preview-image" alt="预览大图">
      <div class="custom-close" @click="dialogVisible = false">
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref ,onMounted ,computed} from 'vue';
import { ElMessage, ElLoading , ElMessageBox} from 'element-plus';
import { request } from '/src/utils/service';
import * as XLSX from 'xlsx';
import { useRoute, useRouter } from 'vue-router';
import {Close, Message,Search, Document,ChatLineRound} from '@element-plus/icons-vue'
const router = useRouter();
const route = useRoute();
interface UserInfo {
  name: string;
  identification: string;
  id: string;
}
interface TableItem {
  id: number;
  username: string;
  identification: string;
  left: string;
  right: string;
  leftId: number;
  rightId: number;
  uploadTime: string ;
  userId:number;
}
const activeIndex = ref(-1);
const apiPrefix = '/api/dr/';
const imageInput = ref<HTMLInputElement>();
const loading = ref(false);
const tableData = ref<TableItem[]>([]);
const tableLoading = ref(false);
const deleteLoading = ref<Record<number, boolean>>({});
const dialogVisible = ref(false);
const selectedImage = ref('');
const excelInput = ref<HTMLInputElement>();
const excelPromiseResolve = ref<((file: File) => void) | null>(null);
const excelPromiseReject = ref<((reason?: any) => void) | null>(null);
const searchName = ref('')
const searchId = ref('')
const userInfo = ref<UserInfo | null>(null)
const uploadUserInfo = ref<UserInfo | null>(null)
// 计算过滤后的数据
const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const nameMatch = userInfo.value?.name.toLowerCase().includes(searchName.value.toLowerCase())
    const idMatch = userInfo.value?.identification.includes(searchId.value)
    return nameMatch && idMatch
  })
})

// 可选：添加搜索按钮触发（如果不需要回车搜索可以删除）
const handleSearch = () => {
  // 这里可以添加额外的搜索逻辑
}
const handlePreviewImage = (imgUrl: string) => {
  selectedImage.value = imgUrl;
  dialogVisible.value = true;
};
const handleReturn =()=>{
  router.push('/upload')
}
const handleImageError = (type) => {
  console.error(`${type}图像加载失败`)
}
const handleRefresh = async () => {
  try {
    await fetchTableData();
    ElMessage.success('数据刷新成功');
  } catch {
    ElMessage.error('刷新失败');
  }
};
const handleAIChat = (row: TableItem) => {
  const chatUrl = `${window.location.origin}/#/chat?Id=${row.leftId}`;
  window.open(chatUrl, '_blank');
};
const handleView = async(row: TableItem) => {
  const imageId= row.leftId;
  const response = await request({
    url: `/api/dr/${imageId}/get_one`,
    method: 'get'
  });
  const resultId = parseInt(
      response.data.image_url.match(/(\d+)_left/)[1]   // 捕获数字部分
  );
  const targetPath = response.data.image_url.replace(/\\[^\\]+$/, '');
  const localFilePath = targetPath.replace(/\//g, '\\');
  const postData = new FormData();
  postData.append('image_url', localFilePath)
  const resultResponse = await request({
    url: `/api/dr/${resultId}/get_result/`,
    method: 'post',
    data: postData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  const UID =resultResponse.data.ID;
  // window.open(`http://localhost:8042/ohif/viewer?StudyInstanceUIDs=${UID}`, "_blank");
  window.open('http://localhost:8042/ohif/viewer?StudyInstanceUIDs=1.2.826.0.1.3680043.8.498.73219315650338268219848172356485325763')
  // router.push(`/detail/${row.id}`);
};
const makePDF = async (row: TableItem) => {
  const imageId= row.leftId;
  const response = await request({
    url: `/api/dr/${imageId}/get_one`,
    method: 'get'
  });
  const resultId = parseInt(
      response.data.image_url.match(/(\d+)_left/)[1]   // 捕获数字部分
  );
  const targetPath = response.data.image_url.replace(/\\[^\\]+$/, '');
  const localFilePath = targetPath.replace(/\//g, '\\');
  const postData = new FormData();
  postData.append('image_url', localFilePath)
  const resultResponse = await request({
    url: `/api/dr/${resultId}/get_result/`,
    method: 'post',
    data: postData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  const data = [
  resultResponse.data.N || 0,  // 0:正常
  resultResponse.data.D || 0,  // 1:糖尿病
  resultResponse.data.G || 0,  // 2:青光眼
  resultResponse.data.C || 0,  // 3:白内障
  resultResponse.data.A || 0,  // 4:AMD
  resultResponse.data.H || 0,  // 5:高血压
  resultResponse.data.M || 0,  // 6:近视
  resultResponse.data.O || 0   // 7:其他
];

// 找到最大值对应的索引
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
  router.push({
    path: '/preview', // 对应路由配置中的 path
    query: {
      leftId: row.leftId,
      rightId: row.rightId,
      id:row.userId*10+maxIndex
    },
  });
}

const fetchTableData = async (showAll: boolean = false) => {
  const userId= route.query.id
  const dirPath = route.query.dirPath
  const uploadUserInfo= await fetchInfo(userId);
  const formatUploadTime = (timeStr: string) => {
    // 格式化为 "YYYY-MM-DD HH:mm"
    return timeStr.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3 $4:$5');
  };
  try {
    userInfo.value = await fetchUserInfo()
    tableLoading.value = true;
    const response = await request({
      url: '/api/dr/get_all/',
      method: 'get'
    });
    const grouped = response.data.reduce((acc, item) => {
      const pathMatch = item.image_url.match(/userimage[\\/]([^\\/]+)[\\/](\d+)_(left|right)\.jpg$/i);
      if (!pathMatch) return acc;
      const [_, directoryName, num, type] = pathMatch;
      const [__, ___, uploadTime] = directoryName.split('-');
      if(directoryName!==dirPath) return acc;
      const key = `${num}_${directoryName}`;
      if (!acc[key]) {
        acc[key] = {
          userId: item.user,
          username: uploadUserInfo.name,
          uploadTime: formatUploadTime(uploadTime),
          identification: uploadUserInfo.identification,
          left: '',
          right: '',
          leftId: -1,
          rightId: -1
        };
      }
      if (type === 'left') {
        acc[key].left = item.image;
        acc[key].leftId = item.id;
      } else {
        acc[key].right = item.image;
        acc[key].rightId = item.id;
      }
      return acc;
    }, {});

    tableData.value = Object.values(grouped)
        .filter((item: any) => item.left && item.right)
        .sort((a: any, b: any) => b.leftId - a.leftId)
        .map((item: any, index,uploadTime) => ({
          ...item,
          id: index + 1,
        }));
  } catch (error) {
    ElMessage.error('获取数据失败');
    console.error('获取表格数据错误:', error);
  } finally {
    tableLoading.value = false;
  }
};
// 删除记录
const handleDelete = async (row: TableItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await Promise.all([
      request({ url: `${apiPrefix}${row.leftId}/`, method: 'delete' }),
      request({ url: `${apiPrefix}${row.rightId}/`, method: 'delete' })
    ]);
    ElMessage.success('删除成功');
    await fetchTableData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};
// 获取用户信息
const fetchUserInfo = async (): Promise<UserInfo> => {
  try {
    const response = await request({
      url: '/api/system/user/user_info/',
      method: 'get'
    });
    return {
      name: response.data.name,
      id: response.data.id,
      identification: response.data.identification
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败');
    throw error;
  }
};
const fetchInfo = async (userId:number): Promise<UserInfo> => {
  try {
    const response = await request({
      url: `/api/system/user/${userId}/get_user_info`,
      method: 'get'
    });
    return {
      name: response.data.name,
      id: response.data.id,
      identification: response.data.identification,
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败');
    throw error;
  }
};
// 处理上传按钮点击
const handleUploadClick = async () => {
  try {
    loading.value = true;
    const userInfo = await fetchUserInfo();
    imageInput.value?.click();
    (window as any).__tempUserInfo = userInfo;
  } catch (error) {
    console.error('上传流程中断:', error);
  } finally {
    loading.value = false;
  }
};
const handleImageSelect = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const allFiles = Array.from(input.files || []);
  input.value = '';

  if (allFiles.length === 0) return;

  // 基础校验
  const invalidFiles = allFiles.filter(file =>
    !/\.jpe?g$/i.test(file.name) || file.size > 5 * 1024 * 1024
  );

  if (invalidFiles.length > 0) {
    ElMessage.warning(`发现${invalidFiles.length}个无效文件，已自动过滤`);
  }

  const validFiles = allFiles.filter(file =>
    /\.jpe?g$/i.test(file.name) && file.size <= 5 * 1024 * 1024
  );

  if (validFiles.length === 0) {
    ElMessage.error('未选取有效图片');
    return;
  }

  try {
    const userInfo = (window as any).__tempUserInfo;
    if (!userInfo?.id) {
      ElMessage.error('用户信息获取失败，请重试');
      return;
    }

    const formData = new FormData();
    formData.append('user', userInfo.id);
    validFiles.forEach(file => formData.append('file', file));

    const loadingInstance = ElLoading.service({
      lock: true,
      text: `正在上传 ${validFiles.length} 个文件...`,
      background: 'rgba(0, 0, 0, 0.7)'
    });

    const response = await request({
      url: '/api/dr/',
      method: 'post',
      data: formData,
      headers: {'Content-Type': 'multipart/form-data'}
    });

    loadingInstance.close();
    ElMessage.success(`成功上传 ${validFiles.length} 张图片`);
    await fetchTableData(true);
  } catch (error) {
    ElMessage.error('上传失败');
    console.error('上传错误:', error);
  } finally {
    input.value = '';
  }
};
onMounted(()=>{

  fetchTableData(true);
})
</script>
<style scoped>
/* 基础变量与全局设置 */
:root {
  font-size: 16px;
}
:deep(.transparent-dialog) {
  background: rgba(64, 64, 64, 0.5) !important;
  backdrop-filter: blur(8px);
  border-radius: 12px;
  overflow: hidden;
}

:deep(.transparent-dialog .el-dialog__header) {
  display: none;
}

:deep(.transparent-dialog .el-dialog__body) {
  padding: 0;
  background: transparent;
}
/* 调整图片预览容器 */
.image-preview-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 80vh;
}

.preview-image {
  max-width: 60vw;
  max-height: 60vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}
/* 容器布局 */
.history-container {
  font-size: 1rem;
  padding: 2rem;
  background: #f8fafc;
  min-height: 100vh;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部操作栏 */
.top-bar {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding: 1.5rem 3rem;
  background: white;
  border-radius: 1rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;

}

.app-title {
  font-size: 3rem;
  color: #1e293b;
  font-weight: 600;
  letter-spacing: -0.025em;
}

/* 操作按钮组 */
.action-container {
  display: flex;
  align-items: center;
  gap: 2rem;
}

.action-buttons {
  display: flex;
  gap: 1.5rem;
}

.flat-button {
  border: none !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  background: dodgerblue !important;
  width: 48px;
  height: 48px;

  &:hover {
    transform: scale(1.2)  !important;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2) !important;
    background: #1a73e8 !important;
  }

  &.el-button--primary {
    color: #409eff !important;
    &:hover { background: #1a73e8 !important; }
  }

  &.el-button--info {
    color: #909399 !important;
    &:hover { background: #909399 !important; }
  }
}
.return-button {
  border: none !important;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s ease !important;
  background: white !important;
  width: 48px;
  height: 48px;

  &:hover {
    transform: scale(1.2) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  }

  &.el-button--primary {
    color: #409eff !important;
    &:hover { background: #e8f4ff !important; }
  }

  &.el-button--info {
    color: #909399 !important;
    &:hover { background: #f4f4f5 !important; }
  }
}
/* 滚动容器 */
.scroll-container {
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 120px);
  padding: 0 20px;
}

/* 卡片视图 */
.card-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 2rem;
  padding: 20px 0;
  transition: all 0.8s ease;
}

.data-card {
  display: flex;
  flex-direction: column;
  min-height: 400px;
  background: white;
  border-radius: 1.5rem;
  padding: 1.5rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  border: 1px solid #e2e8f0;
  opacity: 0; /* 初始不可见 */
  animation: cardEnter 0.6s cubic-bezier(0.4, 0, 0.2, 1) forwards; /* 添加基础动画 */
}

/* 卡片内部元素 */
.card-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1.25rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f1f5f9;
}

.record-id {
  font-weight: 1000;
  font-size: 3rem;
  color: #3b82f6;
}

.upload-time {
  color: #64748b;
  font-size: 2rem;
  white-space: nowrap;
}

/* 眼部预览 */
.eye-container {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-bottom: 1.5rem;
}

.eye-item {
  flex: 1;
  max-width: 400px;
  text-align: center;
}
.report-image {
  width: 100%;
  max-width: 300px;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.image-wrapper {
  height: 250px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.thumbnail-preview {
  height: 100%;
  width: auto;
  max-width: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.02);
    cursor: zoom-in;
  }
}

.image-missing {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  border: 1px dashed #d1d5db;
}

/* 患者信息 */
.patient-info {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-top: 1.5rem;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 0.75rem;
  font-size: 1.5rem;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #475569;
}

/* 卡片操作按钮 */
.card-actions {
  margin-top: auto;
  padding-top: 1rem;
  border-top: 1px solid #f1f5f9;
  display: flex;
  gap: 0.75rem;
  width: 100%;
  justify-content: space-between;

  .el-button {
    flex: 1 1 30%;
    min-width: 90px;
    max-width: calc(33.33% - 0.5rem);
    padding: 8px 12px;
    font-size: 1.2rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    border-radius: 8px !important;
  }
}
.el-button:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
/* 动画效果 - 修复版 */
@keyframes cardEnter {
  from {
    opacity: 0;
    transform: translateY(100px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 手动添加交错延迟 */
.data-card:nth-child(1) { animation-delay: 0.1s; }
.data-card:nth-child(2) { animation-delay: 0.2s; }
.data-card:nth-child(3) { animation-delay: 0.3s; }
.data-card:nth-child(4) { animation-delay: 0.4s; }
.data-card:nth-child(5) { animation-delay: 0.5s; }
.data-card:nth-child(n+6) { animation-delay: 0.6s; }
.eye-label{
  font-size: 20px;
}
.image-container {
  width: 100%;
  aspect-ratio: 1/1; /* 强制1:1宽高比 */
  overflow: hidden;
  display: flex;
  justify-content: center;
  background: #ffffff; /* 可选：添加背景色 */
}
.search-group {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
  transition: width 0.3s;
}

.search-input:focus-within {
  width: 250px;
}

</style>